<!-- 违章待查询 -->
<template>
  <a-modal
    :visible="visible"
    @cancel="visible = false"
    @close="handleClose"
    :title="pageTlt"
    :mask-closable="false"
    :align-center="false"
    class="modal-dialog-wrapper"
    unmount-on-close
    top="30px"
    width="85vw"
  >
    <div style="max-height: 85vh">
      <list-searcher :searchList="searchList" v-model:searchForm="queryParam" @loadData="loadData" />
      <table-index
        :table="table"
        class="custom-table"
        :rowKey="`id`"
        :selectedKeys="selectedRowKeys"
        @loadData="loadData"
        @selection-change="handleSelectionChange"
      >
        <template #table-summary>
          <a-alert>
            <template #icon>
              <icon-exclamation-circle />
            </template>
            <div class="alert-item">渠道车辆未同启程做匹配关系，则不提醒，请提前做好匹配</div>
          </a-alert>
        </template>
        <!-- 订单单号 -->
        <template #orderCode="{ record }">
          <div class="order-info-item">
            <div>自有</div>
            <div>{{ record.orderCode }}</div>
          </div>
          <div class="order-info-item" v-if="record.channelOrderCode">
            <div>渠道</div>
            <div>{{ record.channelOrderCode }}</div>
          </div>
        </template>
        <!-- 承租人信息 -->
        <template #rentMember="{ record }">
          <template v-if="record.memberName || record.memberPhone">
            <div class="link-wrapper">
              <div class="text-link no-link" v-if="record.memberName">{{ record.memberName }}</div>
              <div class="text-link no-link" v-if="record.memberPhone">{{ record.memberPhone }}</div>
            </div>
          </template>
        </template>
        <!-- 交还车人 -->
        <template #staff="{ record }">
          <div class="content-item pickup">
            <div class="flex items-start content-item-name">
              <tag type="primary">交</tag>
              <div class="flex-row flex-1">
                {{ record.giveStaffName || '未指派' }}
              </div>
            </div>
          </div>
          <div class="content-item return">
            <div class="flex items-start content-item-name">
              <tag type="primary">还</tag>
              <div class="flex-1">
                {{ record.returnStaffName || '未指派' }}
              </div>
            </div>
          </div>
        </template>
      </table-index>
    </div>
    <template #footer>
      <a-button @click="visible = false">关闭</a-button>
    </template>
  </a-modal>
</template>

<script setup name="Wzdcxtips" lang="jsx">
  import { ref, reactive, computed } from 'vue'
  import { getOrderViolationQueryList, batchCloseViolation, batchQueryViolationCheck, batchQueryViolation } from '@/api/workplace.js'
  import { Button, Modal, Message } from '@arco-design/web-vue'
  import { IconExclamationCircleFill } from '@arco-design/web-vue/es/icon'
  import { useTable, useFetchTableDataApi } from '@/hooks/table'
  import { useRouter } from 'vue-router'
  const router = useRouter()

  //查询条件
  let queryParam = reactive({})
  const searchList = computed(() => {
    return [
      {
        label: '车牌号',
        prop: 'licenseNoLike',
        type: 'a-input',
      },
      {
        label: '实际还车时间',
        prop: 'startTimeRange',
        type: 'i-range-picker',
        attrs: {
          showTime: true,
          timePickerProps: {
            defaultValue: ['00:00:00', '23:59:59'],
          },
        },
        change: (value = []) => {
          queryParam.startTimeBegin = value[0]
          queryParam.startTimeEnd = value[1]
        },
      },
      {
        label: '车辆当前所属门店',
        prop: 'siteIdList',
        type: 'remote-select',
        attrs: {
          multiple: true,
          type: 'multiple_site_listBystaff',
          popupContainer: '.modal-dialog-wrapper .remote-select-wrapper',
        },
      },
      {
        label: '交车人',
        prop: 'giveStaffNameLike',
        type: 'a-input',
      },
      {
        label: '还车人',
        prop: 'returnStaffNameLike',
        type: 'a-input',
      },
    ]
  })
  // 待处理 - table 配置
  const table = useTable({
    queryParam: queryParam,
    tableHeight: 'calc(100vh - 450px)',
    rowSelection: {
      type: 'checkbox',
      showCheckedAll: true,
      showChecked: (record) => {
        // 违章未处理时可以选择
        return record.warningStatus == 0
      },
    },
    columns: [
      { title: '订单单号', dataIndex: 'orderCode', slotName: 'orderCode', width: 240, fixed: 'left' },
      { title: '订单状态', dataIndex: 'orderStatusName', width: 80 },
      { title: '车牌号', dataIndex: 'carLicenseNo', width: 100 },
      { title: '承租人', dataIndex: 'rentMember', slotName: 'rentMember', width: 100 },
      {
        title: '交/还车人',
        width: 90,
        dataIndex: 'staff',
        slotName: 'staff',
      },
      {
        title: '实际还车时间',
        width: 170,
        dataIndex: 'actualEndTime',
        sortable: {
          sorter: true,
          sortDirections: ['ascend', 'descend'],
        },
      },
      { title: '车辆当前归属门店', width: 150, dataIndex: 'carSiteName' },
      {
        title: '提醒时间',
        width: 170,
        dataIndex: 'warningTime',
        sortable: {
          sorter: true,
          sortDirections: ['ascend', 'descend'],
        },
      },
    ],
    buttons: [
      {
        // 权限为 违章查询列表页 的权限
        permission: 'svms:asstes:violation:query.query',
        label: '查询记录',
        method: () => {
          // 跳转到违章查询列表页
          router.push({ path: '/assets/violation/query' })
        },
      },
      {
        // 权限为 违章-违章查询-查询违章的按钮权限
        permission: 'svms:asstes:violation:query.query',
        label: '批量违章查询',
        method: () => {
          // 选择了订单
          if (selectedRowKeys.value.length > 0) {
            handleQueryViolation('batch')
          } else {
            Message.warning('请选择要批量违章查询的订单')
          }
        },
      },
      {
        // 权限为 违章-违章查询-查询违章的按钮权限
        permission: 'svms:asstes:violation:query.query',
        label: '批量关闭提醒',
        method: () => {
          // 选择了订单
          if (selectedRowKeys.value.length > 0) {
            handleCloseRemind('batch')
          } else {
            Message.warning('请选择要关闭提醒的订单')
          }
        },
      },
    ],
    operates: [
      {
        label: '违章查询',
        // 权限为 违章-违章查询-查询违章的按钮权限
        permission: 'svms:asstes:violation:query.query',
        // 违章未处理时显示操作按钮
        show: (record) => record.warningStatus == 0,
        method: (record) => handleQueryViolation('single', record),
      },
      {
        label: '关闭提醒',
        // 权限为 违章-违章查询-查询违章的按钮权限
        permission: 'svms:asstes:violation:query.query',
        // 违章未处理时显示操作按钮
        show: (record) => record.warningStatus == 0,
        method: (record) => handleCloseRemind('single', record),
      },
    ],
  })

  // 关闭提醒
  const handleCloseRemind = (type, record) => {
    Modal.confirm({
      title: '确认',
      simple: true,
      content: '是否关闭提醒？',
      okText: '确认',
      onBeforeOk: (done) => {
        return new Promise(() => {
          const param = {
            idList: type == 'batch' ? selectedRowKeys.value : [record.id],
          }
          batchCloseViolation(param)
            .then(() => {
              Message.success('关闭成功')
              done(true)
              handleSuccess(type, param.idList)
            })
            .catch(() => {
              done(false)
            })
        })
      },
    })
  }
  // 查询违章
  const handleQueryViolation = (type, record) => {
    const param = {
      idList: type == 'batch' ? selectedRowKeys.value : [record.id],
    }
    // 调用check接口
    batchQueryViolationCheck(param).then((res) => {
      if (res.code == 200) {
        const status = res.result
        if (status == 200) {
          Modal.confirm({
            title: '确认',
            simple: true,
            content: '是否查询违章？',
            okText: '确认',
            onBeforeOk: (done) => {
              return new Promise(() => {
                batchQueryViolation(param)
                  .then(() => {
                    Message.success('已发起查询，请等待1-2分钟，在查询记录中查看结果')
                    done(true)
                    handleSuccess(type, param.idList)
                  })
                  .catch(() => {
                    done(false)
                  })
              })
            },
          })
        } else {
          handleQueryError(status)
        }
      }
    })
  }
  // 处理异常
  const handleQueryError = (status) => {
    const config = {
      showLoginBtn: false,
      tips: '',
    }
    // 余额不足
    if (status == 3001) {
      config.tips = '账户余额不足，请先充值后查询违章'
    }
    // 余额不足
    if (status == 3002) {
      config.tips = '数据正在同步中，当列表中【最近数据更新时间】变更为当天，再操作查询即可'
    }
    // 登录失效
    if (status == 3004) {
      config.showLoginBtn = true
      config.tips = '请先登录查询账号，再操作违章查询'
    }
    // 去登录
    const toLogin = () => {
      // 关闭弹窗
      modal.close()
      // 跳转到违章查询列表页
      router.push({ path: '/assets/violation/query' })
    }
    const modal = Modal.open({
      title: '提示',
      width: '40vw',
      content: (
        <div class="block text-center">
          <IconExclamationCircleFill style="color: #ff7d00; font-size: 40px" />
          <div style="margin: 20px 0 16px">{config.tips}</div>
          {config.showLoginBtn ? (
            <Button type="primary" onClick={toLogin}>
              去登录
            </Button>
          ) : (
            ''
          )}
        </div>
      ),
      hideCancel: true,
      okText: '关闭',
      okButtonProps: {
        type: 'secondary',
      },
    })
  }

  // 处理成功
  const handleSuccess = (type, idList) => {
    // 加载数据
    loadData()
    // 处理 selectedRowKeys
    if (type == 'batch') {
      selectedRowKeys.value = selectedRowKeys.value.filter((item) => {
        return !idList.includes(item)
      })
    }
  }

  // 列表接口调用
  const loadData = useFetchTableDataApi(table, queryParam, getOrderViolationQueryList)
  // 多选
  const selectedRowKeys = ref([])
  const handleSelectionChange = (e) => {
    selectedRowKeys.value = e
  }
  // modal展示
  const visible = ref(false)
  let pageTlt = ref('')
  const open = (label) => {
    pageTlt = label
    visible.value = true
    loadData(1)
  }
  const handleClose = () => {
    // 重置参数
    for (var k in queryParam) {
      queryParam[k] = undefined
    }
    // 重置选中
    selectedRowKeys.value = []
  }

  defineExpose({
    open,
  })
</script>

<style lang="less" scoped>
  .content-item {
    .content-item-name {
      margin-bottom: 4px;

      :deep(.custom-tag) {
        margin-right: 6px;
        position: relative;
        top: 1px;
      }
    }

    .content-item-tag :deep(.custom-tag.default) {
      line-height: 20px;
      padding: 4px 8px;
    }
  }
  .custom-table {
    :deep(.arco-space.arco-space-horizontal) {
      margin-left: 16px;
    }
  }
</style>
